import { onUnmounted } from "vue";
import * as echarts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";

const HANDLER = "_vue_resize_handler";

export const chartResizeDirective = {
  mounted(el, binding) {
    el[HANDLER] = binding.value
      ? binding.value
      : () => {
          const chart = echarts.getInstanceByDom(el);
          if (chart) {
            chart.resize();
          }
        };

    const erd = elementResizeDetectorMaker();
    erd.listenTo(el, el[HANDLER]);

    // 清理工作
    onUnmounted(() => {
      erd.removeListener(el, el[HANDLER]);
      delete el[HANDLER];
    });
  },
};
